package me.nibo.baidumap;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private Context mContext;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    // 是否第一次进入
    private boolean isFirstIn = true;
    // 纬度
    private double mLatitude;
    // 经度
    private double mLongitude;
    // 地址
    private String mAddress;
    // 我的位置图标
    private BitmapDescriptor mIconMyLocation;
    private MyOrientationListener mMyOrientationListener;
    private float mCurrentX;
    // 定位模式
    private MyLocationConfiguration.LocationMode mLocationMode;


    // 地址信息标记图标
    private BitmapDescriptor mMarker;
    private LinearLayout mMarkerLy;
    private ImageView mImage;
    private TextView mMarkerName;
    private TextView mDistance;
    private TextView mZan;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        mContext = this;
        initView();
        initLocation();

        initMarker();
    }

    private void initMarker() {
        mMarker = BitmapDescriptorFactory.fromResource(R.mipmap.maker);
        mMarkerLy = (LinearLayout) findViewById(R.id.ly_marker);
        mImage = (ImageView) findViewById(R.id.iv_marker);
        mMarkerName = (TextView) findViewById(R.id.tv_marker_name);
        mDistance = (TextView) findViewById(R.id.tv_distance);
        mZan = (TextView) findViewById(R.id.tv_zan);
    }

    private void initLocation() {
        mLocationMode = MyLocationConfiguration.LocationMode.NORMAL;
        LocationClientOption option = new LocationClientOption();
        // 坐标类型
        option.setCoorType("bd09ll");
        // 定位成功返回地址
        option.setIsNeedAddress(true);
        // 开启GPS
        option.setOpenGps(true);
        // 每隔1秒钟请求一次定位
        option.setScanSpan(1000);

        mLocationClient = new LocationClient(this, option);
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        mIconMyLocation = BitmapDescriptorFactory.fromResource(R.mipmap.navi_map_gps_locked);
        mMyOrientationListener = new MyOrientationListener(this);
        mMyOrientationListener.setOnOrientationListener(
                new MyOrientationListener.OnOrientationListener() {
                    @Override
                    public void onOrientationChanged(float x) {
//                Log.d(TAG, "方向改变：" + x);
                        mCurrentX = x;
                    }
                });
    }

    private void initView() {
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Log.d(TAG, "点击覆盖物");
                Bundle bundle = marker.getExtraInfo();
                AddressInfo info = (AddressInfo) bundle.getSerializable("info");
                mImage.setImageResource(info.getImage());
                mMarkerName.setText(info.getName());
                mDistance.setText(info.getDistance());
                mZan.setText(info.getZan() + "");

                InfoWindow infoWindow;
                TextView textView = new TextView(mContext);
                textView.setText(info.getName());
                textView.setBackgroundResource(R.drawable.location_tips);
                textView.setTextColor(Color.WHITE);
                textView.setPadding(30, 20, 30, 50);

                LatLng latLng = marker.getPosition();
                Point p = mBaiduMap.getProjection().toScreenLocation(latLng);
                p.y -= 50;
                latLng = mBaiduMap.getProjection().fromScreenLocation(p);
                infoWindow = new InfoWindow(textView, latLng, 0);
                mBaiduMap.showInfoWindow(infoWindow);
                mMarkerLy.setVisibility(View.VISIBLE);
                return true;
            }
        });
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
                mMarkerLy.setVisibility(View.GONE);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_map_common:
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                return true;
            case R.id.menu_map_site:
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                return true;
            case R.id.menu_traffic:
                if (mBaiduMap.isTrafficEnabled()) {
                    mBaiduMap.setTrafficEnabled(false);
                    item.setTitle("实时交通(on)");
                } else {
                    mBaiduMap.setTrafficEnabled(true);
                    item.setTitle("实时交通(off)");
                }
                return true;
            case R.id.menu_my_location:
                centerToMyLoaction();
                return true;
            case R.id.menu_mode_common:
                mLocationMode = MyLocationConfiguration.LocationMode.NORMAL;
                return true;
            case R.id.menu_mode_following:
                mLocationMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                return true;
            case R.id.menu_mode_compass:
                mLocationMode = MyLocationConfiguration.LocationMode.COMPASS;
                return true;
            case R.id.menu_add_overlap:
                addOverlaps(AddressInfo.infos);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 添加覆盖物
     *
     * @param infos 地址信息
     */
    private void addOverlaps(List<AddressInfo> infos) {
        mBaiduMap.clear();
        LatLng latLng = null;
        Marker marker;
        OverlayOptions options;
        for (AddressInfo info : infos) {
            // 经纬度
            latLng = new LatLng(info.getLatitude(), info.getLongitude());
            // 地址图标
            options = new MarkerOptions().position(latLng).icon(mMarker).zIndex(5);
            marker = (Marker) mBaiduMap.addOverlay(options);
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", info);
            marker.setExtraInfo(bundle);
        }
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.setMapStatus(msu);
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
//            Log.d(TAG, "定位成功：" + mCurrentX);
            MyLocationData data = new MyLocationData.Builder()
                    .direction(mCurrentX) // 方向
                    .accuracy(bdLocation.getRadius()) // 精度
                    .latitude(bdLocation.getLatitude()) // 纬度
                    .longitude(bdLocation.getLongitude()) // 经度
                    .build();

            mBaiduMap.setMyLocationData(data);

            mLatitude = bdLocation.getLatitude();
            mLongitude = bdLocation.getLongitude();
            mAddress = bdLocation.getAddrStr();

            // 自定义定位图标
            MyLocationConfiguration config = new MyLocationConfiguration(
                    mLocationMode, true, mIconMyLocation);
            mBaiduMap.setMyLocationConfigeration(config);

            if (isFirstIn) {
                centerToMyLoaction();
                isFirstIn = false;
            }
        }
    }

    /**
     * 定位到我的位置
     */
    private void centerToMyLoaction() {
        LatLng latLng = new LatLng(mLatitude, mLongitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.animateMapStatus(msu);
        Toast.makeText(mContext, mAddress, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        mMyOrientationListener.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
        mMyOrientationListener.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause()，实现地图生命周期管理
        mMapView.onPause();
    }
}
